#include "echo.h"

// ================================================================================

#define BUF_LEN 1024

static void usage() {
  printf("Usage: echo-client <Echo-Server IP address> <Message>\n");
}

static int write_all(int sock, char *buf, int len) {
  while (len) {
    int res = send(sock, buf, len, 0);
    if (res < 0) {
      return res;
    }

    len -= res;
    buf += res;
  }
}

static int read_all(int sock, char *buf, int len) {
  while (len) {
    int res = recv(sock, buf, len, 0);
    if (res < 0) {
      return res;
    }

    len -= res;
    buf += res;
  }
}

int main(int argc, char *argv[]) {
  int sock;
  sockaddr_in_t svr_addr;
  char buf[BUF_LEN];
  char recv_buf[BUF_LEN];
  int msg_len;

  if (argc < 3) {
    usage();
    return 1;
  }

  if (inet_aton(argv[1], &svr_addr.sin_addr) == -1) {
    usage();
    return 1;
  }

  sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock == -1) {
    perror("Failed to create a network socket");
    return 1;
  }

  svr_addr.sin_family = AF_INET;
  svr_addr.sin_port = htons(ECHO_PORT);
  if (connect(sock, (sockaddr_t*)&svr_addr, sizeof(svr_addr)) == -1) {
    perror("Failed to connect to the Echo-Server");
    close(sock);
    return 1;
  }

  memset(recv_buf, BUF_LEN, 0);

  msg_len = strlen(argv[2]);

  if (write_all(sock, argv[2], msg_len) < 0) {
    perror("Error while transmitting the message");
    close(sock);
    return 1;
  }

  if (read_all(sock, recv_buf, msg_len) < 0) {
    perror("Error while transmitting the message");
    close(sock);
    return 1;
  } else {
    printf("%s\n", recv_buf);
  }  

  close(sock);

  return 0;
}
